package com.iceland.common.util;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ResourceReader {

    // 变成驼峰样式
    static String camelize(String input) {
        for (int i = 0; i < input.length(); i++) {
            if(input.substring(i, i+1).equals("-")) {
                input.replace("-", "");
                input = input.substring(0, i) + input.substring(i+1, i+2).toUpperCase() + input.substring(i+2);
            }
            if(input.substring(i, i+1).equals(" ")) {
                input.replace(" ", "");
                input = input.substring(0, i) + input.substring(i+1, i+2).toUpperCase() + input.substring(i+2);
            }
        }
        return input;
    }

    private static Yaml buildYamlInstance(){
        Constructor c = new Constructor();
        c.setPropertyUtils(new PropertyUtils() {
            @Override
            public Property getProperty(Class<? extends Object> type, String name){
                if ( name.indexOf('-') > -1 ) {
                    name = camelize(name);
                }
                // 忽略yaml中无法在类中找到属性的字段
                setSkipMissingProperties(true);
                return super.getProperty(type, name);
            }
        });
        Yaml parser = new Yaml(c);
        return parser;
    }

    public static  <T> T loadYml(Class<T> _class,String fileName){
        Yaml yaml=buildYamlInstance();
        try (InputStream in = ResourceReader.class.getClassLoader().getResourceAsStream(fileName+".yml");) {
            return yaml.loadAs(in, _class);
        } catch (Exception e) {
            log.error("Init yaml failed !", e);
        }
        return null;
    }
   

}
